package com.offcn;

import com.offcn.config.RpcServerConfig;
import com.offcn.dto.RpcRequestParams;
import com.offcn.service.HelloService;
import com.offcn.service.impl.HelloServiceImpl;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class RPCServerStart {
    public static void main(String[] args) {
        //创建服务实例
        HelloService helloService = new HelloServiceImpl();

        try {
            //启动服务器socket监听端口
            ServerSocket serverSocket = new ServerSocket(RpcServerConfig.PORT);
            System.out.println("RPC Server启动:" + RpcServerConfig.ADDRESS + ":" + RpcServerConfig.PORT);
            //服务器启动循环监听客户端连接
            while (true) {
                Socket clientSocket = serverSocket.accept();
                //获取客户端传递的数据,执行反序列化
                ObjectInputStream objectInputStream = new ObjectInputStream(clientSocket.getInputStream());
                //获取客户端传递参数
                Object object = objectInputStream.readObject();
                //定义返回结果
                int result = 0;
                //判断客户端传递的是否是请求参数对象
                if (object instanceof RpcRequestParams) {
                    RpcRequestParams rpcRequestParams = (RpcRequestParams) object;
                    //调用本地服务对象的方法
                    result = helloService.add(rpcRequestParams.getOne(), rpcRequestParams.getTwo());
                }

                //把服务返回结果序列化
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());
                objectOutputStream.writeObject(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}
